package cn.initcap.elasticjob.job;

import cn.initcap.elasticjob.autoconfig.ElasticSimpleJob;
import cn.initcap.elasticjob.model.Order;
import cn.initcap.elasticjob.service.OrderService;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author initcap
 * @date 6/26/19 3:33 PM
 */
@ElasticSimpleJob(
        jobName = "orderCancelJob",
        cron = "0/15 * * * * ?",
        shardingTotalCount = 2,
        overwrite = true
)
public class OrderCancelJob implements SimpleJob {

    private static final int THREAD_SIZE = 4;

    @Autowired
    private OrderService orderService;

    @Override
    public void execute(ShardingContext shardingContext) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.SECOND, -30);
        //订单尾号 % 分片总数 == 当前分片项
        List<Order> orders = orderService.getOrder(now,
                shardingContext.getShardingTotalCount(), shardingContext.getShardingItem());

        if (orders != null && !orders.isEmpty()) {
            ExecutorService es = new ThreadPoolExecutor(THREAD_SIZE, THREAD_SIZE, 0L, TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>());
            for (Order order : orders) {
                es.execute(() -> {
                    //更新条件
                    Integer orderId = order.getId();
                    Date updateTime = order.getUpdateTime();
                    //更新内容
                    //已取消
                    int status = 3;
                    String updateUser = "system";
                    Date updateNow = new Date();

                    orderService.cancelOrder(orderId, updateTime, status, updateUser, updateNow);
                });
            }
            es.shutdown();
        }
    }
}
